package com.bbs.common;

import com.github.houbb.sensitive.word.api.IWordAllow;
import com.github.houbb.sensitive.word.api.IWordDeny;
import com.github.houbb.sensitive.word.support.allow.WordAllows;
import com.github.houbb.sensitive.word.support.deny.WordDenys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @PackageName: org.example.config
 * @ClassName: CustomPhrase
 * @Description: 自定义敏感词和非敏感词配置
 * @Author: Rambo
 * @Data: 2024/6/23 15:20
 */
public class CustomPhrase {
    private static final Logger logger = LoggerFactory.getLogger(CustomPhrase.class);

    // 自定义敏感词
    public static class MyWordDeny implements IWordDeny {

        @Override
        public List<String> deny() {
            List<String> list = new ArrayList<>();
            try {
                Resource mySensitiveWords = new ClassPathResource("custom_phrase_words/bbsSensitiveWords.txt");
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(mySensitiveWords.getInputStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        list.add(line.trim());
                    }
                }
            } catch (IOException ioException) {
                logger.error("读取敏感词文件错误！" + ioException.getMessage());
            }
            return list;
        }
    }

    // 自定义非敏感词
    public static class MyWordAllow implements IWordAllow {

        @Override
        public List<String> allow() {
            List<String> list = new ArrayList<>();
            try {
                Resource myAllowWords = new ClassPathResource("custom_phrase_words/bbsAllowWords.txt");
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(myAllowWords.getInputStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        list.add(line.trim());
                    }
                }
            } catch (IOException ioException) {
                logger.error("读取非敏感词文件错误！" + ioException.getMessage());
            }
            return list;
        }
    }

    // 配置默认敏感词 + 自定义敏感词
    public static final IWordDeny wordDeny = WordDenys.chains(WordDenys.system(), new MyWordDeny());
    // 配置默认非敏感词 + 自定义非敏感词
    public static final IWordAllow wordAllow = WordAllows.chains(WordAllows.system(), new MyWordAllow());
}
